//
//  MainMenuViewController.m
//  CandyCrushClone
//
//  Created by Petar on 2/22/15.
//  Copyright (c) 2015 Nestorov Engineering. All rights reserved.
//

#import "MainMenuViewController.h"
#import "CommunicationManager.h"
#import "Globals.h"
#import <QuartzCore/QuartzCore.h>
#import "RWTViewController.h"
#import "HMIAPHelper.h"
#import "IAPProduct.h"
#import "UIView+Animations.h"
#import "RegistrationViewController.h"
#import "HeroInfo.h"
#import "EnergyManager.h"
#import "AudioController.h"
@import StoreKit;

@interface MainMenuViewController () <UIAlertViewDelegate>

@property (weak, nonatomic) IBOutlet UILabel *energyLabel;
@property (weak, nonatomic) IBOutlet UILabel *onlinePlayersLabel;
@property (weak, nonatomic) IBOutlet UIButton *playButton;
@property (weak, nonatomic) IBOutlet UIButton *rankingButton;
@property (weak, nonatomic) IBOutlet UIView *heroButtonView;
@property (weak, nonatomic) IBOutlet UIButton *heroButton;
@property (weak, nonatomic) IBOutlet UIButton *settingsButton;
@property (weak, nonatomic) IBOutlet UIImageView *gameTitleImageView;
@property (weak, nonatomic) IBOutlet UIView *connectingToServerView;
@property (weak, nonatomic) IBOutlet UIView *buyEnergyPopupView;
@property (weak, nonatomic) IBOutlet UIView *connectingToAppStorePopupView;
@property (weak, nonatomic) IBOutlet UILabel *buyUnlimitedEnergyLabel;

@property (weak, nonatomic) IBOutlet UIImageView *onlinePlayersIndicatorImageView;
@property (weak, nonatomic) IBOutlet UIButton *energyIndicatorImageView;
@property (weak, nonatomic) IBOutlet UIImageView *gameNameImageView;

// Constraints
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *onlinePlayersIndicatorLeftConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *energyIndicatorRightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *gameNameTopConstraint;

@end

@implementation MainMenuViewController
{
    NSInteger _onlinePlayers;
    IAPProduct *_energyProduct;
    CommunicationManager *_communicationManager;
    NSTimer *_timeLeftTimer;
    AudioController *_audioController;
}

- (void)viewDidLoad
{
    
    [super viewDidLoad];
    
    _audioController = [AudioController sharedInstance];
    
    // Not registered
    if ( [[NSUserDefaults standardUserDefaults] valueForKey:PASSWORD_KEY] == nil ) {
        
        [self presentRegistrationVC];
        
    }
    
    _communicationManager = [CommunicationManager sharedManager];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateEnergyLabel) name:kEnergyManagerEnergyReplenished object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onLoggedIn) name:LOGGED_IN object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(synchronizeUserMoney:) name:CMD_GET_AMOUNT_OF_MONEY object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(receiveTransactionCompleteMainMenuNotification)
                                                 name:@"transaction complete"
                                               object:nil];
    
    // Random between 1000 to 1200
    _onlinePlayers = arc4random_uniform(1200 - 1000) + 1000;
    
    [self requestInAppPurchaseProducts];
    
}


- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    
    [self startAnimations];
    
    _energyProduct = [[HMIAPHelper sharedInstance] getEnergyProduct];
    
    [self updateEnergyLabel];
    
    // Not registered so, do Not connect to the server
    if ( [[NSUserDefaults standardUserDefaults] valueForKey:PASSWORD_KEY] == nil ) {
        return;
    }
    
    [self setChosenHeroImage];
    
    if ( [_communicationManager isConnected] == NO ) {
        
        [self showConnectingView];
        
        if ( [_communicationManager isConnecting] == NO ) {
            
            [_communicationManager connectToWebService];
            
        }
        
    } else {
        
        if ( _communicationManager.isLoggedIn == YES ) {
            
            [self updateOnlinePlayers];
            [_communicationManager getAmountOfMoneyFromServer];
        }
        
    }
    
}


- (void)viewDidAppear:(BOOL)animated
{
    
    [super viewDidAppear:animated];
    
    [_audioController playBGMusic];
    
}


- (void)viewWillDisappear:(BOOL)animated
{
    
    [super viewWillDisappear:animated];
    
    [self stopTimeLeftTimer];
    
    if ( SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0") ) {
        
        [self playHideAnimationForPlayButton];
        [self playHideAnimationForView:_rankingButton];
        [self playHideAnimationForView:_heroButtonView];
        [self playHideAnimationForView:_settingsButton];
        
    }
    
}


- (void)startAnimations
{
    
    [self startPlayButtonAnimation];
    
    [_rankingButton startWobbleAnimationAfterDuration:0.5f];
    [_heroButtonView startWobbleAnimationAfterDuration:0.25f];
    [_settingsButton startWobbleAnimationAfterDuration:0.5f];
    
    // Hide views
    _onlinePlayersIndicatorLeftConstraint.constant = -_onlinePlayersIndicatorImageView.frame.size.width;
    _energyIndicatorRightConstraint.constant = -_energyIndicatorImageView.frame.size.width;
    _gameNameTopConstraint.constant = -_gameNameImageView.frame.size.height;
    
    [self.view layoutIfNeeded];
    
    // Show views
    [UIView animateWithDuration:1.3f delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:1 options:(UIViewAnimationOptionCurveEaseOut | UIViewAnimationOptionAllowUserInteraction) animations:^{
        
        _onlinePlayersIndicatorLeftConstraint.constant = 9;
        _energyIndicatorRightConstraint.constant = 7;
        _gameNameTopConstraint.constant = -4;
        
        [self.view layoutIfNeeded];
        
    } completion:nil];
    
}


- (void)setChosenHeroImage
{
    
    HeroInfo *chosenHeroInfo = [HeroInfo getChosenHeroInfo];
    UIImage *heroImage = [UIImage imageNamed:[NSString stringWithFormat:@"animal_%zd", chosenHeroInfo.type]];
    [_heroButton setBackgroundImage:heroImage forState:UIControlStateNormal];
    
}


- (void)presentRegistrationVC
{
    
    RegistrationViewController *registrationVC = [self.storyboard instantiateViewControllerWithIdentifier:@"RegistrationVC"];
    [self.navigationController presentViewController:registrationVC animated:NO completion:nil];
    
}


- (IBAction)didPressPlayButton:(id)sender
{
    
    [_audioController playButtonClick];
    
    if ( [_communicationManager isConnected] == YES && _communicationManager.isLoggedIn == YES ) {
        
        BOOL hasEnoughEnergy = [self hasEnoughEnergy];
        
        if ( hasEnoughEnergy == YES ) {
            
            // Init game for QUICK_GAME Type
            RWTViewController *gameViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"GameVC"];
            gameViewController.gameType = QUICK_GAME;
            
            [self.navigationController pushViewController:gameViewController animated:YES];
            
        } else {
            
            [self configureBuyEnergyText];
            [self showPopupView:_buyEnergyPopupView];
            
        }
        
    } else {
        
        [self showConnectingView];
        
        if ( [_communicationManager isConnecting] == NO ) {
            
            [_communicationManager connectToWebService];
            
        }
        
    }
    
}


- (IBAction)didPressEnergyIndicatorButton:(id)sender
{
    
    [_audioController playButtonClick];
    
    BOOL isPurchasedUnlimitedEnergy = [[NSUserDefaults standardUserDefaults] boolForKey:IS_PURCHASED_UNLIMITED_ENERGY_KEY];
    
    if ( isPurchasedUnlimitedEnergy ) {
        return;
    }
    
    [self configureBuyEnergyText];
    [self showPopupView:_buyEnergyPopupView];
    
}


- (IBAction)didPressBuyEnergyButton:(id)sender
{
    
    [_audioController playButtonClick];
    
    if ( _energyProduct != nil ) {
        
        if ( _energyProduct.allowedToPurchase == YES ) {
            
            [self showPopupView:_connectingToAppStorePopupView];
            
            // Buy Energy
            [[HMIAPHelper sharedInstance] buyProduct:_energyProduct];
            
        } else {
            
            NSLog(@"_energyProduct can NOT be bought");
            
        }
        
    } else {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Something went wrong. Please try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        
        [self requestInAppPurchaseProducts];
        
        NSLog(@"Don't have products yet...");
        
    }
    
}


- (IBAction)didPressCancelPopupButton:(id)sender
{
    
    [_audioController playButtonClick];
    [self hidePopup:_buyEnergyPopupView];
    
}


- (IBAction)didPressCloseAppStorePopupButton:(id)sender
{
    
    [_audioController playButtonClick];
    [self hidePopup:_connectingToAppStorePopupView];
    
}


- (BOOL)hasEnoughEnergy
{
    
    NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
    
    NSInteger currentEnergy = [settings integerForKey:CURRENT_ENERGY_KEY];
    BOOL isPurchasedUnlimitedEnergy = [settings boolForKey:IS_PURCHASED_UNLIMITED_ENERGY_KEY];
    
    if ( isPurchasedUnlimitedEnergy == YES || currentEnergy >= 1 ) {
        
        return YES;
        
    }
    
    return NO;
    
}


#pragma mark - In-App Purchases

- (void)requestInAppPurchaseProducts
{
    
    [[HMIAPHelper sharedInstance] requestProductsWithCompletionHandler:^(BOOL success, NSArray *products) {
        
        if ( success ) {
            
            _energyProduct = [[HMIAPHelper sharedInstance] getEnergyProduct];
            
        }
        
    }];
    
}


- (void)receiveTransactionCompleteMainMenuNotification
{
    
    [self performSelector:@selector(updateEnergyLabel) withObject:nil afterDelay:1];
    
    [self hidePopup:_connectingToAppStorePopupView];
    [self hidePopup:_buyEnergyPopupView];
    
}


- (void)updateOnlinePlayers
{
    
    // Generates number between -20 to 20
    NSInteger newPlayers = arc4random_uniform(40);
    newPlayers -= 20;
    
    _onlinePlayers += newPlayers;
        
    // Keep it between 900 to 1300
    NSInteger biggerThan900 = MAX(_onlinePlayers, 900);
    NSInteger smallerThan1300 = MIN(biggerThan900, 1300);
    _onlinePlayers = smallerThan1300;
    
    [_onlinePlayersLabel setText:[NSString stringWithFormat:@"%zd",_onlinePlayers]];
    
}


- (void)startPlayButtonAnimation
{
    
    _playButton.transform = CGAffineTransformMakeScale(0.7,0.7); // 0.3
    
    [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.75 initialSpringVelocity:1 options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionAllowUserInteraction animations:^{
        
        _playButton.transform = CGAffineTransformMakeScale(1,1);
        
    } completion:nil];
    
    [UIView animateWithDuration:2.5 delay:0 usingSpringWithDamping:0.2 initialSpringVelocity:1 options:UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat | UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionAllowUserInteraction animations:^{
        
        _playButton.transform = CGAffineTransformMakeScale(1.09,1.09);
        
    } completion:nil];
    
}


-(void)playHideAnimationForPlayButton
{
    
    [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        
        _playButton.transform = CGAffineTransformMakeScale(1,1);
        
    } completion:^(BOOL finished) {
        [_playButton stopAllAnimations];
    }];
    
}


-(void)playHideAnimationForView:(UIView *)view
{
    
    [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        
        view.transform = CGAffineTransformMakeScale(0,0);
        
    } completion:^(BOOL finished) {
        [view stopAllAnimations];
    }];
    
}


-(void)updateEnergyLabel
{
    
    NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];

    BOOL isPurchasedUnlimitedEnergy = [settings boolForKey:IS_PURCHASED_UNLIMITED_ENERGY_KEY];
    
    if ( isPurchasedUnlimitedEnergy == YES ) {
        [self stopTimeLeftTimer];
        [_energyLabel setText:@"∞"];
        [_energyLabel setFont:[_energyLabel.font fontWithSize:35]];
        [_energyLabel sizeToFit];
        return;
    }
    
    NSInteger currentEnergy = [settings integerForKey:CURRENT_ENERGY_KEY];
    
    if ( currentEnergy == 0 ) {
        
        [self startTimeLeftTimer];
        
    } else {
    
        [self stopTimeLeftTimer];
        NSString *energyText = [NSString stringWithFormat:@"%zd", currentEnergy];
        [_energyLabel setText:energyText];
        
    }
    
}


- (void)startTimeLeftTimer
{
    
    [self stopTimeLeftTimer];
    
    _timeLeftTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self
                                                selector: @selector(updateTimeLeftLabel) userInfo: nil repeats: YES];
    
}


- (void)stopTimeLeftTimer
{
    
    // Reset timer
    if ( _timeLeftTimer ) {
        
        [_timeLeftTimer invalidate];
        _timeLeftTimer = nil;
        
    }
    
}


- (void)updateTimeLeftLabel
{
    
    [_energyLabel setText:[[EnergyManager sharedInstance] getTimeToReplanishEnergy]];
    
}


- (void)synchronizeUserMoney:(NSNotification *)notification
{
    
    NSDictionary *userInfo = notification.userInfo;
    
    NSInteger amountOfMoney = [userInfo[AMOUNT_OF_MONEY] integerValue];
    
    if ( amountOfMoney > 0 ) {
        
        // set user money
        [[NSUserDefaults standardUserDefaults] setInteger:amountOfMoney forKey:USER_MONEY_KEY];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
    }
    
}


#pragma mark - Connection methods
- (void)onLoggedIn
{
    
    [_connectingToServerView setHidden:YES];
    [self updateOnlinePlayers];
    [_communicationManager getAmountOfMoneyFromServer];
    
}


#pragma mark - Helper methods

- (void)showPopupView:(UIView *)popupView
{
    
    popupView.superview.hidden = NO;
    popupView.superview.alpha = 0;
    
    [UIView animateWithDuration:0.5f animations:^{
        
        popupView.superview.alpha = 1;
        
    }];
    
}


- (void)hidePopup:(UIView *)popupView
{
    
    // Hide PopupView
    if ( popupView.superview.isHidden == NO ) {
        
        [UIView animateWithDuration:0.5f animations:^{
            
            popupView.superview.alpha = 0;
            
        } completion:^(BOOL finished) {
            
            popupView.superview.hidden = YES;
            
        }];
        
    }
    
}


- (void)showConnectingView
{
    
    [_connectingToServerView setHidden:NO];
    
}


- (void)configureBuyEnergyText
{
    
    if ( _energyProduct != nil ) {
        
        // format skProduct price to local price
        NSNumberFormatter *priceFormatter = [[NSNumberFormatter alloc] init];
        [priceFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
        [priceFormatter setLocale:_energyProduct.skProduct.priceLocale];
        
        NSString *buyEnergyText = [NSString stringWithFormat:@"Buy UNLIMITED energy only for %@ ?", [priceFormatter stringFromNumber:_energyProduct.skProduct.price]];
        
        [_buyUnlimitedEnergyLabel setText:buyEnergyText];
        
    }
    
}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

    if ( [[segue identifier] isEqualToString:@"StoreSegue"]    ||
         [[segue identifier] isEqualToString:@"SettingsSegue"] ||
         [[segue identifier] isEqualToString:@"RankingsSegue"] ) {
        
        [_audioController playButtonClick];
        
    }
    
}


- (BOOL)prefersStatusBarHidden
{
    return YES;
}

@end
